package com.neishenmo.sochatapp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.neishenmo.sochatapp.R;
import com.neishenmo.sochatapp.network.ApiConstract;
import com.neishenmo.sochatapp.network.ApiPresenter;
import com.neishenmo.sochatapp.util.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 创建人： wushixin
 * 创建日期：2018/5/23
 * 内容：
 */

public class LoginActivity extends AppCompatActivity implements ApiConstract.view {
    @BindView(R.id.edit_iphone)
    EditText editIphone;
    private ApiPresenter apiPresenter = new ApiPresenter(this);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);


    }

    @Override
    public void showErrMsg(String msg) {

    }

    @Override
    public void showInfo(String string) {
        Log.e("sss",string);

        try {
            JSONObject jsonObject=new JSONObject(string);
            if (jsonObject.getInt("code")==200){
                Intent intent=new Intent(LoginActivity.this,VerificationActivity.class);
                intent.putExtra("iphone",editIphone.getText().toString());
                if (jsonObject.getJSONObject("data").getInt("msgType")==1){
                    intent.putExtra("msgType",1);
                } else {
                    intent.putExtra("msgType",0);
                }
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 发送外部验证码（登陆、注册）
     */
    private void initHttpSendExternalCode(String iphone) {
        Map<String, String> map = new HashMap<>();
        map.put("telephone", iphone);

        MediaType JSON = MediaType.parse("application/json; charset=UTF-8");
        RequestBody requestBody = RequestBody.create(JSON, Utils.mapToJson(map));
        apiPresenter.loadSendExternalCode(requestBody);
    }

    @OnClick({R.id.img_back, R.id.img_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_next:
                if (editIphone.getText().toString().length()>0) {
                    initHttpSendExternalCode(editIphone.getText().toString());
                }
                break;
        }
    }
}
